package servlet;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import model.Study;
import model.User;
import DAO.ParticipationDao;
import DAO.StudyDao;
import DAO.StudyFineDao;
import DAO.UserDao;
import DAO.UserDetailDao;

public class StudyAcceptAction implements Action {

	@Override
	public ActionForward execute(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		HttpSession session=request.getSession();
		ActionForward forward=new ActionForward();
		
		ParticipationDao participationDao = new ParticipationDao();
		StudyDao studyDao = new StudyDao();
		UserDao userDao = new UserDao();
		
	
		int studyId = request.getParameter("studyId") != null
				&& request.getParameter("studyId") != "" ? Integer
				.parseInt(request.getParameter("studyId")) : 0;
		int userId = session.getAttribute("userid") != null
				&& session.getAttribute("userid") != "" ? Integer
				.parseInt((String)session.getAttribute("userid")) : 0;
		if (userId < 1) {
			session.invalidate();
			Util.ShowError(response, "로그인해주세요");
		}
		if (studyId < 1) {
			Util.ShowError(response, "잘못 된 접근입니다");
		}
		
		
		Study study = new Study();
		study = studyDao.getStudyInfo(studyId);
		User user = new User();
		UserDetailDao userDetailDao = new UserDetailDao();
	
		
		String memId = request.getParameter("targetId") != null
				&& request.getParameter("targetId") != "" ? request.getParameter("targetId") : null;
		int targetId = Integer.parseInt(userDao.getUserIdByMemId(memId));
		user=userDao.getUserInfo(targetId);
		
		StudyFineDao studyFineDao = new StudyFineDao();
		
		
		if(userId==study.getUid()){
			
			
			if(user.getPoint()>=study.getDeposit()){
				participationDao.updateParticipation(studyId, targetId);
				userDetailDao.updateOngoingStudy(targetId);
			
			}
			else {
				Util.ShowError(response, "잔액이 부족합니다.");
				return forward;
			}
			
		}
		else {
			Util.ShowError(response, "권한이 없습니다.");
			return forward;
		}
		
		
		request.setAttribute("studyId", studyId);
		
		forward.setPath("./Accept.Study");
		return forward;

	}

}
